from selenium_base import *
from PIL import Image, ImageChops

url = 'http://47.103.13.124:8001/captcha_slide_puzzle_canvas'

before = 'before.png'
after = 'after.png'


def get_diff_position(before, after):
    before_img = Image.open(before)
    after_img = Image.open(after)
    # PNG文件是PngImageFile对象，与RGBA模式
    # ImageChops.difference方法只能对比RGB模式，所以需要转换一下格式
    before_img = before_img.convert('RGB')
    after_img = after_img.convert('RGB')
    # 对比2张图片中像素不同的位置
    diff = ImageChops.difference(before_img, after_img)
    # 获取图片差异位置坐标
    # 坐标顺序为左、上、右、下
    diff_position = diff.getbbox()
    position_x = diff_position[0]
    return position_x


try:
    brower = get_brower()
    brower.get(url)
    brower.add_cookie({"name": "session",
                       "value": ".eJyrViotTi1SsqpWyiyOT0zJzcxTsjLQUcrJTwexSopKU3WUcvOTMnNSlayUDM3gQEkHrDE-M0XJyhjCzkvMBSmKKTVNMjMDkiamFkq1tQDfeR3n.YLOC4w.Xbnx1QbrvUh8OUPb5jauC_Aau9U"})
    brower.get(url)

    # 定位到canvas
    jigsawCanvas = brower.find_element_by_id('jigsawCanvas')
    # 保存背景图
    jigsawCanvas.screenshot(before)
    action = webdriver.ActionChains(brower)
    jigsawCircle = brower.find_element_by_id('jigsawCircle')

    # 显示目标缺口
    action.click_and_hold(jigsawCircle).move_by_offset(1, 0).release().perform()
    # 执行script，隐藏拖动滑块
    script = """
    var cralwer_missblock = document.getElementById('missblock');
    cralwer_missblock.style['visibility'] = 'hidden';
    """
    brower.execute_script(script)
    jigsawCanvas.screenshot(after)
    offset_x = get_diff_position(before, after)
    # 执行script，显示拖动滑块，方便我判断移动距离
    script = """
    var cralwer_missblock = document.getElementById('missblock');
    cralwer_missblock.style['visibility'] = 'visible';
    """
    brower.execute_script(script)
    # 移动滑块
    # 保存图片的宽度与Canvas显示的宽度，差2倍（这是我4k屏幕导致的）
    action.release().perform()
    offset_x = (offset_x / 2) - 10
    action.click_and_hold(jigsawCircle).move_by_offset(offset_x, 0).perform()
    time.sleep(0.5)
    action.release().perform()
finally:
    time.sleep(5)
    brower.close()
